<?php


namespace App\HttpController\Admin;


use App\Model\Roles\RolesBean;
use App\Model\Roles\RolesModel;
use EasySwoole\EasySwoole\Logger;
use Carbon\Carbon;

class Role extends Auth {

    /**
     * 列表
     * @return bool|void
     * @throws \Exception
     */
    public function index(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $page = $data['page'] ?? 1;
        $model = new RolesModel();
        $list = $model->paginate($page);
        return $this->writeJson(0,$list);
    }

    /**
     * 更新
     * @return bool
     */
    public function update(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $bean = new RolesBean($data);
        $model = new RolesModel();
        if($bean->getId()){
            //修改
            $result = $model->update($bean,$data);
            if($result){
                return $this->writeJson(0,null,'编辑成功');
            }
            return $this->writeJson(1,null,'编辑失败');
        }else{
            //新增
            $bean->setCreatedAt(Carbon::now());
            $result = $model->create($bean);
            if($result){
                return $this->writeJson(0,null,'新增成功');
            }
            return $this->writeJson(1,null,'新增失败');
        }

    }

    /**
     * 删除
     * @return bool
     * @throws \Exception
     */
    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $bean = new RolesBean(['id' => $id]);
        $model = new RolesModel();
        $res = $model->destroy($bean);
        return $this->writeJson(0,$res);
    }



    public function access(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $bean = new RolesBean(['id' => $id]);
        $model = new RolesModel();
        $info = $model->find($bean);
        return $this->writeJson(0,$info->getRules());
    }


    public function accessUpdate(){
        $request = $this->request();
        $data = $request->getRequestParam();
        if(empty($data['id'])){
            return $this->writeJson(1,null,'参数错误');
        }
        $bean = new RolesBean(['id' => $data['id']]);
        $model = new RolesModel();
        $data['rules'] = json_encode($data['rules']);
        $result = $model->update($bean,$data);
        if($result){
            return $this->writeJson(0,null,'更新成功');
        }
        return $this->writeJson(1,null,'更新失败');
    }


}
